package com.jstyle.jclifexd.NetWork;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;


import com.jstyle.jclifexd.NetWork.api.JstyleApi;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.NetWorkConast;
import com.jstyle.jclifexd.utils.SHA1;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;

import java.security.DigestException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/3/24.
 */

public class NetWorkUtil {


    private static class NetWorkUtilInstance{
        private static final  NetWorkUtil netWorkUtil=new NetWorkUtil();
    }
    private JstyleApi fomoApi;
    public static final String downloadUrl="http://www.le-young.com/files/1755/gps/cep_pak.bin";


    private final static String baseUrl="https://app.getfomofit.com/fomofit/";
    public static NetWorkUtil getInstance(){
        return NetWorkUtilInstance.netWorkUtil;
    }
    private NetWorkUtil(){
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        SSLContext sslContext = getSSLContext();
        OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(logging).sslSocketFactory(sslContext.getSocketFactory()).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        fomoApi=retrofit.create(JstyleApi.class);
    }

    public JstyleApi getJstyleApi(){
        return this.fomoApi;
    }

    public static void addSHA1(Map<String,Object> map) {
        map.put(NetWorkConast.key_timestamp, getTimestamp());
        map.put(NetWorkConast.key_appkey, NetWorkConast.fomoKey);
        map.put(NetWorkConast.key_secret, NetWorkConast.fomoSecret);
        String sha1 = "";
        try {
            sha1 = SHA1.SHA1(map);
        } catch (DigestException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        map.remove(NetWorkConast.key_secret);
        map.put(NetWorkConast.key_sign,sha1);
    }
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }
    public static String getUserId(){
        String token="";
        String authUserID= SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_AUTH_USERID);
        if(!TextUtils.isEmpty(authUserID))return  authUserID;
        String phone= SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_PHONE);
        if(TextUtils.isEmpty(phone))return "";
        UserInfo us= UserInfoDaoManager.getUser(phone);
        if(us!=null)return us.getUserId()+"";
        return token;
    }
    public static UserInfo getUser(){
        String phone= SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_PHONE);
        if(TextUtils.isEmpty(phone))return null;
        UserInfo us= UserInfoDaoManager.getUser(phone);
        return us;
    }
    public static String getTimestamp() {
        return System.currentTimeMillis() / 1000 + "";
    }

    private  SSLContext getSSLContext() {
        SSLContext s_sSLContext;
        try {
            s_sSLContext = SSLContext.getInstance("TLS");

            //信任所有证书 （官方不推荐使用）
            s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                      return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {

                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {

                }
            }}, new SecureRandom());

            return s_sSLContext;
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }

}
